<?php
namespace Orx\Etl\Extractor\Source\Reader;
/**
 * Contact Import File Reader
 * Handle format translation
 *
 * @author Xavier VILAIN
 * @package Orx\Etl\Extractor\Source\Reader
 * @license #license-orx-etl#
 * 
 */
class SpreadSheet {

	/**
	 * 
	 * Read the file expecting a spreadsheet 
	 * @param string $filename
	 * @param \Hive\Contact\Import\Format
	 */
	public static function read($filename,$format) {
		$limit = $format->row_limit;
		$errors = $data = array();
		// Activate phpExcel
		\Fox::instance()->usePHPExcel();
		\PHPExcel_Calculation::getInstance()->setCalculationCacheEnabled(false);
		// Create reader and get principal sheet
		$objReader = \PHPExcel_IOFactory::createReaderForFile($filename);
		$objReader->setReadDataOnly(false);
		$objPHPExcel = $objReader->load($filename);
		$sheet = $objPHPExcel->getSheet(0);
		$rowCount = 1;
		$exit = false;
		foreach($format->items() as $item) {
			$colNumber  = 'A';
			for($i=1;$i<$item->col_number;$i++) {
				$colNumber++;
			}
			$fields[$colNumber] = $item;
		}
		// Read File
		while(!$exit && $rowCount < $limit) {
			$rowCount++;
			$lineData = null;
			foreach($fields as $colNumber => $item) {
				$cellId = $colNumber.$rowCount;
				// Get Cell Value
				$value = $sheet->getCell("$cellId")->getValue();
				// Check if the item is mandatory
				if($item->mandatory > 0 && empty($value)) {
					$errors[] = Msg(\Hive::BUNDLE,\Hive::ERR_EMPY_FIELD_IN_ROW_COLUMN,$rowCount,$colNumber,$item->label());
					break;
				}
				// Parse Value & Check Format
				switch ($item->datatype) {
					// Alpha numeric
					case 1:
						
						break;
					// Alpha numeric
					case 3:
						break;
					// Do nothing
					default;
				}
				$lineData[$item->attribute] = utf8_decode($value);
			}
			if(is_array($lineData)) {
				$data[] = $lineData;
			}
		}
		return array('data' => $data,'errors' => $errors);
	}
	
	/**
	 * 
	 * Parse First Line (Should Contain Headers)
	 * 
	 * @param string $filename
	 * @param Orx\Etl\Extractor\Source
	 * @return array
	 */
	public static function readFirstRow($filename,$format)  {
		$data = array();
		// Activate phpExcel
		\Fox::instance()->usePHPExcel();
		\PHPExcel_Calculation::getInstance()->setCalculationCacheEnabled(false);
		// Create reader and get principal sheet
		$objReader = \PHPExcel_IOFactory::createReaderForFile($filename);
		$objReader->setReadDataOnly(false);
		$objPHPExcel = $objReader->load($filename);
		$sheet = $objPHPExcel->getSheet(0);
		// Read File
		$colNumber = 'A';
		$exit = false;
		while(!$exit) {
			$rowCount = 1;
			$cellId = $colNumber.$rowCount;
			// Get Cell Value
			$value = $sheet->getCell("$cellId")->getValue();
			if(empty($value)) {
				$exit = true;
			} else {
				$data[] = $value;
			}
		}
		return $data;
	}
}